package com.yangming.springboot.deepin.playTest;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @创建人 ym
 * @创建时间 2021/4/8 0008
 * @描述
 **/
public class ConnectionTest {

    private static ConnectionPool pool = new ConnectionPool(10);

    //让所有runnable线程同时启动
    private static CountDownLatch start = new CountDownLatch(1);

    //主线程等待所有的runnable线程全部结束才会结束
    private static CountDownLatch end;

    public static void main(String[] args) throws Exception{
        int threadCount = 20;
        end = new CountDownLatch(threadCount);
        int count = 20;
        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();
        for (int i=0; i < threadCount; i++){
            Thread thread = new Thread(new ConnectionRunner(count, got, notGot), "connectionRunnerThread");
            thread.start();
        }
        start.countDown();
        end.await();
        System.out.println("total invoke: " + (threadCount * count));
        System.out.println("got connection : " + got);
        System.out.println("not got connection : " + notGot);
    }

    private static class ConnectionRunner implements Runnable{
        int count;
        AtomicInteger got;
        AtomicInteger notGot;
        public ConnectionRunner(int count, AtomicInteger got, AtomicInteger notGot){
            this.count = count;
            this.got = got;
            this.notGot = notGot;
        }

        @Override
        public void run(){
            try{
                //调用await把当前线程加入start队列,等待start.coutdown唤醒并启动所有线程
                start.await();
            }catch(Exception e){
                e.printStackTrace();
            }

            while(count > 0){
                try{
                    Connection connection = pool.fetchConnection(1000);
                    if (connection != null){
                        try{
                            connection.createStatement();
                            connection.commit();
                        }finally{
                            pool.releaseConnection(connection);
                            got.incrementAndGet();
                        }
                    }else{
                        notGot.incrementAndGet();
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally{
                    count--;
                }
            }
            end.countDown();
        }
    }
}
